package poi;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

import java.util.*;

/**
 * 住宿安排 解析
 *
 * @author likai
 */
@Slf4j
public class ParseDocxTable2Accommodation extends BaseDocumentParse<Accommodation> {

    private static final ParseDocxTable2Accommodation INSTANCE = new ParseDocxTable2Accommodation();

    private ParseDocxTable2Accommodation() {
    }

    public static ParseDocxTable2Accommodation getInstance() {
        return INSTANCE;
    }

    @Override
    public Collection<Accommodation> parseDoxcTable(XWPFTable xwpfTable, Collection<Accommodation> collection) {
        // 获取一个表格中的所有行
        final List<XWPFTableRow> rows = xwpfTable.getRows();

        final int i = nextPosition();
        final int j = nextPosition();
        final int k = nextPosition();
        final int m = nextPosition();

        final int rowsSize = rows.size();
        for (int row = 1; row < rowsSize; row++) {
            // 获取一行中的所有的单元格
            final XWPFTableRow xwpfTableRow = rows.get(row);
            final List<XWPFTableCell> cells = xwpfTableRow.getTableCells();
            final Accommodation accommodation = new Accommodation();
            for (int col = 0; col < cells.size(); col++) {
                // 打印每个单元格的内容
                final XWPFTableCell cell = cells.get(col);
                final String cellText = cell.getText();
                final String noBlankCellText = RegUtils.replaceAllSpace(cellText);

                if (col == i) {
                    accommodation.setUserName(noBlankCellText);
                } else if (col == j) {
                    accommodation.setPosition(noBlankCellText);
                } else if (col == k) {
                    accommodation.setRoomNo(noBlankCellText);
                } else if (col == m) {
                    accommodation.setCarNo(noBlankCellText);
                }
            }
            boolean add = collection.add(accommodation);
            if (!add) {
                // 同一文件存在重复数据
                throw new RuntimeException("同一文件存在重复行程安排[" + accommodation.getUserName() + ", " + accommodation.getPosition() + ", " + accommodation.getRoomNo() + "]");
            }
            collection.add(accommodation);
        }
        return collection;
    }

}
